import oss2

from settings import Setting


def upload_file_to_oss(local_file, relative_file, oss_type='ali'):
    url = ''
    if oss_type == 'ali':
        auth, bucket_name, end_point = get_ali_oss_auth()
        bucket = oss2.Bucket(auth, end_point, bucket_name)
        bucket.put_object_from_file(relative_file, local_file)
        oss_host = end_point.split('://')[1]
        url = "http://{}.{}/{}".format(bucket_name, oss_host, relative_file)
    return url


def get_ali_oss_auth():
    access_key = Setting.oss_access_key
    access_secret = Setting.oss_access_secret
    end_point = Setting.oss_end_point
    bucket_name = Setting.oss_bucket_name
    auth = oss2.Auth(access_key, access_secret)
    return auth, bucket_name, end_point


def list_oss_directory(prefix, oss_type='ali'):
    if oss_type == 'ali':
        auth, bucket_name, end_point = get_ali_oss_auth()
        bucket = oss2.Bucket(auth, end_point, bucket_name)
        for obj in oss2.ObjectIteratorV2(bucket, prefix=prefix, delimiter='/', fetch_owner=True):
            if obj.is_prefix():  # 判断obj为文件夹。
                print('directory: ' + obj.key)
            else:  # 判断obj为文件。
                print('file: ' + obj.key)
                print('file owner display name: ' + obj.owner.display_name)
                print('file owner id: ' + obj.owner.id)
    else:
        pass
